import styles from './index.module.scss'
import { NavBar, Form, Input, List, Button, Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { codeAction, loginAction } from '@/store/action/user'
import { useEffect, useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
// 表单数据类型

let timeId: NodeJS.Timeout
export default function Login() {
  const location = useLocation<{ from: string }>()
  const history = useHistory()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const inputRef = useRef<InputRef>(null)
  const [timeNum, setTimeNum] = useState(0)
  // 表单校验成功时,登录
  const onFinish = async (values: LoginForm) => {
    await dispatch(loginAction(values))
    // 提示两秒后跳转至首页
    Toast.show({
      content: '登录成功',
      duration: 2000,
      afterClose() {
        if (location.state?.from) {
          // 有来源地址
          history.push(location.state?.from)
        } else {
          // 跳转页面
          history.push('/')
        }
      },
    })
  }
  // 获取验证码
  const codeClick = async () => {
    console.log('点击code')

    try {
      const res = await form.validateFields(['mobile'])
      // console.log(res)
      await dispatch(codeAction(res.mobile))
      setTimeNum((timeNum) => 6)
      timeId = setInterval(() => {
        setTimeNum((timeNum) => {
          if (timeNum === 0) {
            clearInterval(timeId)
            return 0
          }
          return timeNum - 1
        })
        console.log(timeNum)
      }, 1000)
    } catch (error) {
      // console.log([error])
      inputRef.current?.focus()
    }
  }
  useEffect(() => {
    return () => {
      clearInterval(timeId)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      {/* 表单 */}
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{ mobile: '13911111111', code: '246810' }}
        >
          <Form.Item
            name="mobile"
            className="login-item"
            rules={[
              { required: true, message: '必填' },
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机号格式不正确',
              },
            ]}
          >
            <Input placeholder="请输入用户名" ref={inputRef}></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span
                className="code-extra"
                onClick={timeNum <= 0 ? codeClick : undefined}
              >
                发送验证码{timeNum}
              </span>
            }
          >
            <Form.Item
              name="code"
              className="login-item"
              rules={[
                { required: true, message: '必填' },
                { pattern: /^\d{6}$/, message: '请输入六位验证码' },
              ]}
            >
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              color="primary"
              type="submit"
              block
              className="login-submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
